<?php

/**
 * Cust Return to supplier head
 */
class CRtSH extends AppModel {

    var $name = 'CRtSH';
    var $useTable = 'cust_return_to_supplier_heads';
    var $displayField = 'return_no';
    var $hasMany = array(
        'CRtS' => array(
            'foreignKey' => 'cust_return_to_supplier_head_id',
        )
    );
    var $belongsTo = array(
        'Supplier',
        'Customer' => array(
            'fields' => array('id', 'cust_no', 'name')
        ),
        'Site' => array(
            'fields' => array('id', 'site_no', 'name')
        ),
        'CRS' => array(
            'foreignKey' => 'cust_return_status_id',
        ),
        'User' => array(
            'foreignKey' => 'collector_id',
            'fields' => array('username', 'name')
        )
    );
    var $validate = array(
        'return_no' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty'),
                'message' => 'Return no. is required.',
                'required' => true,
            ),
            'isUnique' => array(
                'rule' => 'isUnique',
                'message' => 'This Stock in no is already taken.',
                'on' => 'create'
            ),
        ),
        'return_date' => array(
            'rule' => array('date', 'dmy'),
            'message' => 'Return date is required.',
            'required' => true,
        ),
        'customer_id' => array(
            'rule' => 'notEmpty',
            'message' => 'Customer is required.',
            'required' => true,
        ),
        'site_id' => array(
            'rule' => 'notEmpty',
            'message' => 'Site is required.',
            'required' => true,
        ),
        'supplier_id' => array(
            'rule' => 'notEmpty',
            'message' => 'Vendor is required.',
            'required' => true,
        ),
    );

    function beforeSave() {
        if (isset($this->data['CRtSH']['return_date'])) {
            $this->data['CRtSH']['return_date'] = $this->dateFormatBeforeSave($this->data['CRtSH']['return_date']);
        }
        return true;
    }

    function afterFind($results) {
        if (isset($custStockOutReturnHead['CRtSH'])) {
            foreach ($results as &$custStockOutReturnHead) {
                if (isset($custStockOutReturnHead['CRtSH']['return_date'])) {
                    $custStockOutReturnHead['CRtSH']['return_date'] = $this->dateFormatAfterFind($custStockOutReturnHead['CRtSH']['return_date']);
                }
            }
        }
        return $results;
    }

    /**
     * Custom Query สร้าง Query มาเองให้เป็นรูปแบบที่เหมาะสมสำหรับหน้า print
     * @param int $id cust_stock_in_head_id
     * @return array data
     */
    function findForPrintByid($id) {
        $this->contain(array('Customer', 'Site', 'Supplier', 'CRS',
            'CRtS' => array('Product' => array('supplier_part_no', 'text', 'Unit'), 'CustProductSite')
                )
        );
        $data = $this->findById($id);

        $this->CRtS->bindModel(array(
            'hasMany' => array(
                'ProductSerial' => array(
                    'foreignKey' => 'cust_stock_in_id',
                    'conditions' => array(
                        'cust_stock_out_type' => CRtS::CUST_STOCK_OUT_TYPE
                    )
                )
            )
                )
        );

        $Product = $this->CRtS->Product;
        $PS = $this->CRtS->ProductSerial;
        $CL = $PS->CustLocation;

        // วนลูปรายการ CRtS
        foreach ($data['CRtS'] as &$cr) {
            // หา Location ที่มีอยู่ใน CRtS รายการนี้
            $psCLs = $PS->find('all', array(
                        'fields' => array('DISTINCT cust_location_id'),
                        'conditions' => array(
                            'cust_stock_out_id' => $cr['id'],
                            'cust_stock_out_type' => CRtS::CUST_STOCK_OUT_TYPE,
                            'product_id' => $cr['product_id']
                        )
                            )
            );

            // แปะ Location ที่ได้เข้า CRtS
            foreach ($psCLs as $psCl) {
                $CL->contain();
                $custLocation = $CL->findById($psCl['ProductSerial']['cust_location_id']);

                // option สำหรับ query product serial
                $options = array(
                    'contain' => array(),
                    'conditions' => array(
                        'cust_stock_out_id' => $cr['id'],
                        'cust_stock_out_type' => CRtS::CUST_STOCK_OUT_TYPE,
                        'product_id' => $cr['product_id'],
                        'cust_location_id' => $psCl['ProductSerial']['cust_location_id']
                    )
                );

                // นับจำนวนที่ stock out ใน location นี้
                $ps_count = $PS->find('count', $options);

                // ถึง เฉพาะ Product Serial ที่มี Serial no หรือ other information (ถ้าไม่มีจะออกมา 1 แถว)
                $options['fields'] = array('DISTINCT serial_no', 'other_information');
                $ps = $PS->find('all', $options);

                $custLocation['return_qty'] = $ps_count;
                $custLocation['PS'] = $ps;

                $cr['ProductLocation'][] = $custLocation;
            }
        }
        return $data;
    }

}

?>
